package org.vnl.platform.web.impl.util;

import java.io.IOException;
import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FacesContextUtil {
    
    private static FacesContextUtil instance;
    
    private FacesContextUtil() {
        
    }
    
    public static FacesContextUtil getInstance() {
        if (instance == null) {
            instance = new FacesContextUtil();
        }
        return instance;
    }

    public FacesContext getContext() {
        return FacesContext.getCurrentInstance();
    }
    
    public Locale getLocale() {
        return getContext().getViewRoot().getLocale();
    }
    
    public void setLocale(Locale locale) {
        getContext().getViewRoot().setLocale(locale);
    }
    
    public void setSessionAttribute(String name, Object obj) {
        getContext().getExternalContext().getSessionMap().put(name, obj);
    }
    
    public Object getSessionAttribute(String name) {
        return getContext().getExternalContext().getSessionMap().get(name);
    }
    
    public void removeSessionAttribute(String name) {
        getContext().getExternalContext().getSessionMap().remove(name);
    }
    
    public String getRequestParameter(String name) {
        return getContext().getExternalContext().getRequestParameterMap().get(name);
    }
    
    public void setRequestAttribute(String name, Object value) {
        getContext().getExternalContext().getRequestMap().put(name, value);
    }
    
    public Object getRequestAttribute(String name) {
        return getContext().getExternalContext().getRequestMap().get(name);
    }
    
    public HttpServletRequest getHttpRequest() {
        return (HttpServletRequest) getContext().getExternalContext().getRequest();
    }

    public HttpServletResponse getHttpResponse() {
        return (HttpServletResponse) getContext().getExternalContext().getResponse();
    }
    
    public void sendRedirect(String url) throws IOException {
        getContext().getExternalContext().redirect(url);
    }
    
    public void showView(String viewPath) {
        FacesContext fc = getContext();
        fc.setViewRoot(fc.getApplication().getViewHandler().createView(fc, viewPath));
    }
    
    public void responseComplete() {
        getContext().responseComplete();
    }
    
    public String getContextPath() {
        return getHttpRequest().getContextPath();
    }
    
    public void addMessage(String msg) {
        getContext().addMessage("", new FacesMessage(msg));
    }
    
    public void addMessage(String id, String msg) {
        getContext().addMessage(id, new FacesMessage(msg));
    }
    
    
}
